<template>
  <div class="departments-container">
    <van-nav-bar
      title="科室导航"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 科室搜索 -->
    <div class="search-section px-4 py-3">
      <van-search
        v-model="searchText"
        placeholder="搜索科室名称"
        shape="round"
        @search="onSearch"
      />
    </div>

    <!-- 科室分类标签页 -->
    <van-tabs v-model="activeTab" sticky swipeable animated>
      <van-tab title="门诊科室">
        <van-tree-select
          :active-id="activeOutpatientId"
          :selected-id="selectedOutpatientId"
          @update:active-id="activeOutpatientId = $event"
          @update:selected-id="selectedOutpatientId = $event"
          :items="outpatientDepartments"
          class="custom-tree"
        />
      </van-tab>
      <van-tab title="住院科室">
        <van-tree-select
          :active-id="activeInpatientId"
          :selected-id="selectedInpatientId"
          @update:active-id="activeInpatientId = $event"
          @update:selected-id="selectedInpatientId = $event"
          :items="inpatientDepartments"
          class="custom-tree"
        />
      </van-tab>
    </van-tabs>

    <!-- 科室详情弹出层 -->
    <van-popup
      v-model="showDetail"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <div class="department-detail">
        <van-nav-bar
          :title="currentDepartment?.name"
          left-arrow
          @click-left="showDetail = false"
        />

        <!-- 科室简介 -->
        <div class="intro-section p-4">
          <div class="text-lg font-bold mb-2">科室简介</div>
          <div class="text-gray-600">{{ currentDepartment?.introduction }}</div>
        </div>

        <!-- 科室位置 -->
        <van-cell-group inset class="my-2">
          <van-cell title="门诊位置" :value="currentDepartment?.location" />
          <van-cell title="咨询电话" :value="currentDepartment?.phone" is-link @click="handleCall" />
        </van-cell-group>

        <!-- 出诊时间 -->
        <div class="schedule-section p-4">
          <div class="text-lg font-bold mb-2">出诊时间</div>
          <van-cell-group inset>
            <van-cell title="上午" value="8:00 - 12:00" />
            <van-cell title="下午" value="14:00 - 18:00" />
          </van-cell-group>
        </div>

        <!-- 医生团队 -->
        <div class="doctors-section p-4">
          <div class="section-header flex justify-between items-center mb-2">
            <span class="text-lg font-bold">医生团队</span>
            <van-button size="small" plain type="primary" @click="router.push(`/department/${currentDepartment?.id}/doctors`)">
              查看全部
            </van-button>
          </div>
          <van-cell-group inset>
            <van-cell v-for="doctor in currentDepartment?.doctors" :key="doctor.id" :title="doctor.name" :label="doctor.title" is-link>
              <template #icon>
                <van-image
                  round
                  width="40"
                  height="40"
                  :src="doctor.avatar"
                  class="mr-3"
                />
              </template>
            </van-cell>
          </van-cell-group>
        </div>

        <!-- 预约按钮 -->
        <div class="fixed-bottom p-4">
          <van-button 
            type="primary" 
            block 
            round
            @click="handleAppointment"
          >
            立即预约
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getDepartments } from '../api'

const router = useRouter()
const searchText = ref('')
const activeTab = ref(0)
const showDetail = ref(false)
const currentDepartment = ref(null)

// 门诊科室相关
const activeOutpatientId = ref('')
const selectedOutpatientId = ref('')
const outpatientDepartments = ref([])

// 住院科室相关
const activeInpatientId = ref('')
const selectedInpatientId = ref('')
const inpatientDepartments = ref([])

// 加载科室数据
const loadDepartments = async () => {
  try {
    const res = await getDepartments()
    
    // 处理门诊科室数据
    outpatientDepartments.value = res.outpatient.map(dept => ({
      text: dept.name,
      id: dept.id,
      children: dept.children?.map(child => ({
        text: child.name,
        id: child.id,
        dept: child
      }))
    }))

    // 处理住院科室数据
    inpatientDepartments.value = res.inpatient.map(dept => ({
      text: dept.name,
      id: dept.id,
      children: dept.children?.map(child => ({
        text: child.name,
        id: child.id,
        dept: child
      }))
    }))
  } catch (error) {
    console.error('获取科室列表失败：', error)
    showToast('获取科室列表失败')
  }
}

// 搜索科室
const onSearch = () => {
  if (!searchText.value) return
  
  // TODO: 实现科室搜索功能
  showToast('搜索功能开发中')
}

// 监听科室选择
const watchDepartmentSelection = (id, departments) => {
  if (!id) return
  
  // 查找选中的科室
  for (const dept of departments.value) {
    const selected = dept.children?.find(child => child.id === id)
    if (selected) {
      currentDepartment.value = selected.dept
      showDetail.value = true
      return
    }
  }
}

// 监听门诊科室选择
watch(selectedOutpatientId, (id) => {
  watchDepartmentSelection(id, outpatientDepartments)
})

// 监听住院科室选择
watch(selectedInpatientId, (id) => {
  watchDepartmentSelection(id, inpatientDepartments)
})

// 处理电话咨询
const handleCall = () => {
  if (!currentDepartment.value?.phone) return
  window.location.href = `tel:${currentDepartment.value.phone}`
}

// 处理预约
const handleAppointment = () => {
  if (!currentDepartment.value?.id) return
  router.push({
    path: '/registration',
    query: { departmentId: currentDepartment.value.id }
  })
}

onMounted(() => {
  loadDepartments()
})
</script>

<style scoped>
.departments-container {
  min-height: 100vh;
  background-color: var(--background-color);
}

.custom-tree {
  height: calc(100vh - 200px);
}

.department-detail {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: 80px;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding-bottom: env(safe-area-inset-bottom);
}

:deep(.van-tree-select__item) {
  font-size: 14px;
}

:deep(.van-tree-select__item--active) {
  color: var(--van-primary-color);
}
</style> 